package cn.yangtianxia.basic.controller;

import cn.yangtianxia.basic.util.AjaxResult;
import cn.yangtianxia.basic.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

   /**
    * 文件的上传
    * @param file
    * @return
    */
   @PostMapping
   public AjaxResult upload(@RequestPart(value = "file",required = true) MultipartFile file){
      try {
         String filename = file.getOriginalFilename();
         String exName = filename.substring(filename.lastIndexOf(".") + 1);
         String resultPath = FastdfsUtil.upload(file.getBytes(), exName);
         return AjaxResult.me().setResultObj(resultPath);
      } catch (IOException e) {
         e.printStackTrace();
         return AjaxResult.me().setSuccess(false).setMessage("系统繁忙请稍后重试");
      }
   }

   /**
    * 文件的删除
    * @param path
    * @return
    */
   @DeleteMapping
   public AjaxResult delete(String path){
      try {
         String pathTemp = path.substring(1);// group1/M00/03/56/rBE3kWJBaH2AJuSPAAVL-CQTDAM709.jpg
         String groupName = pathTemp.substring(0, pathTemp.indexOf("/"));// group1
         String fileName = pathTemp.substring(pathTemp.indexOf("/")+1);// M00/03/56/rBE3kWJBaH2AJuSPAAVL-CQTDAM709.jpg
         FastdfsUtil.delete(groupName,fileName);
         return AjaxResult.me();
      } catch (Exception e) {
         e.printStackTrace();
         return AjaxResult.me().setSuccess(false).setMessage("系统繁忙请稍后重试");
      }
   }
}
